#!/usr/bin/env bash

# -e : Exit immediately if a command exits with a non-zero status.
# -u : Treat unset variables as an error when substituting.
# -o pipefail : A pipeline fails if any command in the pipeline fails.
set -euo pipefail

# Define color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
BOLD='\033[1m'
NC='\033[0m' # No Color

curdir="$(cd "$(dirname $(realpath ${BASH_SOURCE[0]}))"; pwd)"
export DOTMY="$curdir"

pushd "$curdir" > /dev/null

# check support os
OS=$(uname -s)
case $OS in
    (Linux) ;;
    (Darwin) ;;
    (*)
        echo -e "${RED}⚠️ Unknown \$(uname -s): ${BOLD}$OS${NC}"
        exit 1
        ;;
esac

mkdir -p "$HOME/.local/bin"

PYTHON=python
if ! which uv >/dev/null 2>&1; then
    if [[ -z "${NO_INSTALL_UV:-}" ]]; then
        echo -e "${YELLOW}🌐 Installing uv...${NC}"
        curl -LsSf https://astral.sh/uv/install.sh | sh
        uv python install 3.13 --default
    else
        echo -e "${YELLOW}⚠️ \$NO_INSTALL_UV set, skipping uv installation${NC}"

        if ! which $PYTHON >/dev/null 2>&1; then
            echo -e "${YELLOW}⚠️ python not found${NC}"

            if ! which python3 >/dev/null 2>&1; then
                echo -e "${RED}⚠️ python3 not installed, exiting..${NC}"
                exit 1
            fi

            if which update-alternatives >/dev/null 2>&1; then
                SDIR="/usr/bin"
                DDIR="/usr/bin"
                PRIOR=0
                sudo update-alternatives --install $DDIR/python $PYTHON $SDIR/python3 $PRIOR
                # exitcode=$?
                # if [[ $exitcode != 0 ]]; then
                #     echo "${RED}⚠️ update-alternatives failed to install python3 as python, exiting..${NC}"
                #     exit $exitcode
                # fi
            else
                PYTHON=python3
            fi
        fi
    fi
else
    echo -e "${GREEN}🟢 uv found: ${BOLD}$(uv --version)${NC}"
fi

if [[ -f "$HOME/.local/bin/env" ]]; then
    . "$HOME/.local/bin/env"
fi

if which uv >/dev/null 2>&1; then
    uv sync
fi

if [[ -d ".venv" ]]; then
    if [[ -n "${VIRTUAL_ENV:-}" ]]; then
        echo -e "${YELLOW}⚠️ uv already activated, skipping activation${NC}"
    else
        echo -e "${CYAN}🔵 Activating python venv...${NC}"
        . ".venv/bin/activate"
    fi
    $PYTHON -m site
fi

./profiles/set-current.sh || exit 1

if [[ ! -d ./private ]]; then
    # 此时应该没有 ~/.ssh 目录，所以先使用 HTTP 协议
    git clone --single-branch --branch main https://gitee.com/hsupu/dotmy-profiles.git private
    # git clone --single-branch --branch main git@gitee.com:hsupu/dotmy-profiles.git private
    pushd private > /dev/null || exit 1
    ./set-current.sh || exit 1

    ssh -T git@gitee.com
    git remote set-url origin git@gitee.com:hsupu/dotmy-profiles.git
    popd > /dev/null
    git remote set-url origin git@gitee.com:hsupu/dotmy.git
fi

# downgrade mainly for type hinting
# 3.7 不支持写法 "|"，用 "Optional[T]" 代替
# 3.9 不支持写法 "T|None"
if [[ "$($PYTHON --version)" =~ ^"Python 3"\.(7|8|9)\. ]]; then
    remap_py="./src/remap.py37"
else
    remap_py="./src/remap.py"
fi

if [[ -e ./profiles/current/mapping.py ]]; then
    mapfile=./profiles/current/mapping.py
else
    OS=$(uname -s)
    case $OS in
        (Linux)
            if [[ -n "${WSL_DISTRO_NAME}" ]]; then
                mapfile=./profiles/base/wsl/mapping.py
            else
                mapfile=./profiles/base/linux/mapping.py
            fi
            ;;
        (Darwin)
            mapfile=./profiles/base/mac/mapping.py
            ;;
    esac
fi

echo -e "${CYAN}🎵 remap${NC}"
$PYTHON $remap_py --map-file $mapfile

echo -e "${CYAN}🎵 sudo remap${NC}"
sudo $PYTHON $remap_py --map-file $mapfile

echo -e "${CYAN}🎵 init shell${NC}"
if which zsh >/dev/null 2>&1; then
    export ZDOTDIR="$HOME/.config/zsh"
    mkdir -p "$ZDOTDIR"
    ./shells/zsh/enable.sh
else
    ./shells/bash/enable.sh
fi

popd > /dev/null

true
